Visualisasi data dengan ggplot

Pengantar ggplot2

ggplot2 adalah salah satu paket visualisasi data yang paling banyak digunakan dalam bahasa pemrograman R. Paket ini dikembangkan oleh Hadley Wickham dan merupakan bagian dari ekosistem tidyverse. ggplot2 didasarkan pada prinsip Grammar of Graphics, yang memungkinkan pengguna untuk membangun grafik dengan cara yang sistematis dan terstruktur. Dengan ggplot2, Anda dapat membuat berbagai jenis visualisasi, mulai dari grafik sederhana hingga grafik yang kompleks, hanya dengan beberapa baris kode. Hal ini menjadikan ggplot2 sebagai alat yang sangat berguna bagi para analis data dan ilmuwan data.

Salah satu keunggulan utama ggplot2 adalah fleksibilitasnya. Pengguna dapat dengan mudah menyesuaikan elemen visual seperti warna, ukuran, dan bentuk titik, serta menambahkan berbagai komponen seperti label, judul, dan tema. Dengan menggunakan ggplot2, Anda dapat membuat visualisasi yang tidak hanya informatif tetapi juga menarik secara visual. Selain itu, ggplot2 mendukung berbagai jenis data, termasuk data numerik dan kategorikal, sehingga dapat digunakan dalam berbagai konteks analisis.

Komunitas pengguna ggplot2 sangat besar, dan ada banyak sumber daya yang tersedia untuk membantu Anda belajar dan menguasai paket ini. Dokumentasi resmi ggplot2 menyediakan panduan lengkap dan contoh penggunaan, sementara banyak tutorial dan kursus online juga tersedia untuk membantu Anda memahami cara menggunakan ggplot2 secara efektif. Untuk informasi lebih lanjut, Anda dapat mengunjungi dokumentasi resmi ggplot2dan tutorial ggplot2 di R for Data Science.

#introduction ggplot2

ggplot2 menggunakan pendekatan berbasis komponen untuk membangun grafik. Setiap grafik terdiri dari beberapa elemen dasar:

  1. Data: Sumber data yang akan divisualisasikan.
  2. Aesthetics (aes): Menentukan bagaimana data dipetakan ke elemen visual (misalnya, sumbu x dan y, warna, ukuran).
  3. Geometries (geom): Jenis grafik yang digunakan (misalnya, titik, garis, histogram).
  4. Statistics: Menghitung statistik yang diperlukan untuk grafik.
  5. Coordinates: Menentukan sistem koordinat.

#Dasar-dasar materi ggplot2

Berikut adalah contoh-contoh dasar penggunaan ggplot2:

###menampikan “hello, world” sederhana

print("hello,world")
## [1] "hello,world"

###contoh ringkasan data

summary(cars)
##      speed           dist       
##  Min.   : 4.0   Min.   :  2.00  
##  1st Qu.:12.0   1st Qu.: 26.00  
##  Median :15.0   Median : 36.00  
##  Mean   :15.4   Mean   : 42.98  
##  3rd Qu.:19.0   3rd Qu.: 56.00  
##  Max.   :25.0   Max.   :120.00

Including Plots

You can also embed plots, for example:

###Membuat Grafik Titik

library(ggplot2)
data <- data.frame  (x = rnorm (100), y = rnorm (100))
ggplot(data, aes(x = x, y = y)) + 
  geom_point() +
  labs(title = "plot titik", x = "sumbu x", y = "sumbu y") +
  theme_dark()

###Faceting dan warna Berdasarkan Grup

data <- data.frame  (x = rnorm (100), y = rnorm (100), grup = sample(c("A", "B", "C", "D"), 100, replace =TRUE))

ggplot(data, aes (x= x, y= y, color = grup)) +
  geom_point() +
  facet_wrap(~ grup)+
  scale_color_manual(values = c("A" = "black", "B" ="red", "C" = "green", "D" = "brown")) +
  theme_dark()

#Read data

Pada bagian ini, kita akan membaca data dari file CSV menggunakan paket readr:

library(readr)
lizard <-read_csv("lizards.csv")
## Rows: 1628 Columns: 16
## ── Column specification ────────────────────────────────────────────────────────
## Delimiter: ","
## chr (10): date, scientific_name, common_name, zone, site, plot, spp, sex, rc...
## dbl  (6): pit, toe_num, sv_length, total_length, weight, pc
## 
## ℹ Use `spec()` to retrieve the full column specification for this data.
## ℹ Specify the column types or set `show_col_types = FALSE` to quiet this message.
View (lizard)

###Membuat Grafik dari Data CSV

#plot titik dasar
ggplot(lizard, aes (x= total_length, y= weight)) +
  geom_point()

  labs(title ="plot titik", x = "total_length", y = "weight")
## $x
## [1] "total_length"
## 
## $y
## [1] "weight"
## 
## $title
## [1] "plot titik"
## 
## attr(,"class")
## [1] "labels"
  theme_dark()
## List of 136
##  $ line                            :List of 6
##   ..$ colour       : chr "black"
##   ..$ linewidth    : num 0.5
##   ..$ linetype     : num 1
##   ..$ lineend      : chr "butt"
##   ..$ arrow        : logi FALSE
##   ..$ inherit.blank: logi TRUE
##   ..- attr(*, "class")= chr [1:2] "element_line" "element"
##  $ rect                            :List of 5
##   ..$ fill         : chr "white"
##   ..$ colour       : chr "black"
##   ..$ linewidth    : num 0.5
##   ..$ linetype     : num 1
##   ..$ inherit.blank: logi TRUE
##   ..- attr(*, "class")= chr [1:2] "element_rect" "element"
##  $ text                            :List of 11
##   ..$ family       : chr ""
##   ..$ face         : chr "plain"
##   ..$ colour       : chr "black"
##   ..$ size         : num 11
##   ..$ hjust        : num 0.5
##   ..$ vjust        : num 0.5
##   ..$ angle        : num 0
##   ..$ lineheight   : num 0.9
##   ..$ margin       : 'margin' num [1:4] 0points 0points 0points 0points
##   .. ..- attr(*, "unit")= int 8
##   ..$ debug        : logi FALSE
##   ..$ inherit.blank: logi TRUE
##   ..- attr(*, "class")= chr [1:2] "element_text" "element"
##  $ title                           : NULL
##  $ aspect.ratio                    : NULL
##  $ axis.title                      : NULL
##  $ axis.title.x                    :List of 11
##   ..$ family       : NULL
##   ..$ face         : NULL
##   ..$ colour       : NULL
##   ..$ size         : NULL
##   ..$ hjust        : NULL
##   ..$ vjust        : num 1
##   ..$ angle        : NULL
##   ..$ lineheight   : NULL
##   ..$ margin       : 'margin' num [1:4] 2.75points 0points 0points 0points
##   .. ..- attr(*, "unit")= int 8
##   ..$ debug        : NULL
##   ..$ inherit.blank: logi TRUE
##   ..- attr(*, "class")= chr [1:2] "element_text" "element"
##  $ axis.title.x.top                :List of 11
##   ..$ family       : NULL
##   ..$ face         : NULL
##   ..$ colour       : NULL
##   ..$ size         : NULL
##   ..$ hjust        : NULL
##   ..$ vjust        : num 0
##   ..$ angle        : NULL
##   ..$ lineheight   : NULL
##   ..$ margin       : 'margin' num [1:4] 0points 0points 2.75points 0points
##   .. ..- attr(*, "unit")= int 8
##   ..$ debug        : NULL
##   ..$ inherit.blank: logi TRUE
##   ..- attr(*, "class")= chr [1:2] "element_text" "element"
##  $ axis.title.x.bottom             : NULL
##  $ axis.title.y                    :List of 11
##   ..$ family       : NULL
##   ..$ face         : NULL
##   ..$ colour       : NULL
##   ..$ size         : NULL
##   ..$ hjust        : NULL
##   ..$ vjust        : num 1
##   ..$ angle        : num 90
##   ..$ lineheight   : NULL
##   ..$ margin       : 'margin' num [1:4] 0points 2.75points 0points 0points
##   .. ..- attr(*, "unit")= int 8
##   ..$ debug        : NULL
##   ..$ inherit.blank: logi TRUE
##   ..- attr(*, "class")= chr [1:2] "element_text" "element"
##  $ axis.title.y.left               : NULL
##  $ axis.title.y.right              :List of 11
##   ..$ family       : NULL
##   ..$ face         : NULL
##   ..$ colour       : NULL
##   ..$ size         : NULL
##   ..$ hjust        : NULL
##   ..$ vjust        : num 1
##   ..$ angle        : num -90
##   ..$ lineheight   : NULL
##   ..$ margin       : 'margin' num [1:4] 0points 0points 0points 2.75points
##   .. ..- attr(*, "unit")= int 8
##   ..$ debug        : NULL
##   ..$ inherit.blank: logi TRUE
##   ..- attr(*, "class")= chr [1:2] "element_text" "element"
##  $ axis.text                       :List of 11
##   ..$ family       : NULL
##   ..$ face         : NULL
##   ..$ colour       : chr "grey30"
##   ..$ size         : 'rel' num 0.8
##   ..$ hjust        : NULL
##   ..$ vjust        : NULL
##   ..$ angle        : NULL
##   ..$ lineheight   : NULL
##   ..$ margin       : NULL
##   ..$ debug        : NULL
##   ..$ inherit.blank: logi TRUE
##   ..- attr(*, "class")= chr [1:2] "element_text" "element"
##  $ axis.text.x                     :List of 11
##   ..$ family       : NULL
##   ..$ face         : NULL
##   ..$ colour       : NULL
##   ..$ size         : NULL
##   ..$ hjust        : NULL
##   ..$ vjust        : num 1
##   ..$ angle        : NULL
##   ..$ lineheight   : NULL
##   ..$ margin       : 'margin' num [1:4] 2.2points 0points 0points 0points
##   .. ..- attr(*, "unit")= int 8
##   ..$ debug        : NULL
##   ..$ inherit.blank: logi TRUE
##   ..- attr(*, "class")= chr [1:2] "element_text" "element"
##  $ axis.text.x.top                 :List of 11
##   ..$ family       : NULL
##   ..$ face         : NULL
##   ..$ colour       : NULL
##   ..$ size         : NULL
##   ..$ hjust        : NULL
##   ..$ vjust        : num 0
##   ..$ angle        : NULL
##   ..$ lineheight   : NULL
##   ..$ margin       : 'margin' num [1:4] 0points 0points 2.2points 0points
##   .. ..- attr(*, "unit")= int 8
##   ..$ debug        : NULL
##   ..$ inherit.blank: logi TRUE
##   ..- attr(*, "class")= chr [1:2] "element_text" "element"
##  $ axis.text.x.bottom              : NULL
##  $ axis.text.y                     :List of 11
##   ..$ family       : NULL
##   ..$ face         : NULL
##   ..$ colour       : NULL
##   ..$ size         : NULL
##   ..$ hjust        : num 1
##   ..$ vjust        : NULL
##   ..$ angle        : NULL
##   ..$ lineheight   : NULL
##   ..$ margin       : 'margin' num [1:4] 0points 2.2points 0points 0points
##   .. ..- attr(*, "unit")= int 8
##   ..$ debug        : NULL
##   ..$ inherit.blank: logi TRUE
##   ..- attr(*, "class")= chr [1:2] "element_text" "element"
##  $ axis.text.y.left                : NULL
##  $ axis.text.y.right               :List of 11
##   ..$ family       : NULL
##   ..$ face         : NULL
##   ..$ colour       : NULL
##   ..$ size         : NULL
##   ..$ hjust        : num 0
##   ..$ vjust        : NULL
##   ..$ angle        : NULL
##   ..$ lineheight   : NULL
##   ..$ margin       : 'margin' num [1:4] 0points 0points 0points 2.2points
##   .. ..- attr(*, "unit")= int 8
##   ..$ debug        : NULL
##   ..$ inherit.blank: logi TRUE
##   ..- attr(*, "class")= chr [1:2] "element_text" "element"
##  $ axis.text.theta                 : NULL
##  $ axis.text.r                     :List of 11
##   ..$ family       : NULL
##   ..$ face         : NULL
##   ..$ colour       : NULL
##   ..$ size         : NULL
##   ..$ hjust        : num 0.5
##   ..$ vjust        : NULL
##   ..$ angle        : NULL
##   ..$ lineheight   : NULL
##   ..$ margin       : 'margin' num [1:4] 0points 2.2points 0points 2.2points
##   .. ..- attr(*, "unit")= int 8
##   ..$ debug        : NULL
##   ..$ inherit.blank: logi TRUE
##   ..- attr(*, "class")= chr [1:2] "element_text" "element"
##  $ axis.ticks                      :List of 6
##   ..$ colour       : chr "grey20"
##   ..$ linewidth    : 'rel' num 0.5
##   ..$ linetype     : NULL
##   ..$ lineend      : NULL
##   ..$ arrow        : logi FALSE
##   ..$ inherit.blank: logi TRUE
##   ..- attr(*, "class")= chr [1:2] "element_line" "element"
##  $ axis.ticks.x                    : NULL
##  $ axis.ticks.x.top                : NULL
##  $ axis.ticks.x.bottom             : NULL
##  $ axis.ticks.y                    : NULL
##  $ axis.ticks.y.left               : NULL
##  $ axis.ticks.y.right              : NULL
##  $ axis.ticks.theta                : NULL
##  $ axis.ticks.r                    : NULL
##  $ axis.minor.ticks.x.top          : NULL
##  $ axis.minor.ticks.x.bottom       : NULL
##  $ axis.minor.ticks.y.left         : NULL
##  $ axis.minor.ticks.y.right        : NULL
##  $ axis.minor.ticks.theta          : NULL
##  $ axis.minor.ticks.r              : NULL
##  $ axis.ticks.length               : 'simpleUnit' num 2.75points
##   ..- attr(*, "unit")= int 8
##  $ axis.ticks.length.x             : NULL
##  $ axis.ticks.length.x.top         : NULL
##  $ axis.ticks.length.x.bottom      : NULL
##  $ axis.ticks.length.y             : NULL
##  $ axis.ticks.length.y.left        : NULL
##  $ axis.ticks.length.y.right       : NULL
##  $ axis.ticks.length.theta         : NULL
##  $ axis.ticks.length.r             : NULL
##  $ axis.minor.ticks.length         : 'rel' num 0.75
##  $ axis.minor.ticks.length.x       : NULL
##  $ axis.minor.ticks.length.x.top   : NULL
##  $ axis.minor.ticks.length.x.bottom: NULL
##  $ axis.minor.ticks.length.y       : NULL
##  $ axis.minor.ticks.length.y.left  : NULL
##  $ axis.minor.ticks.length.y.right : NULL
##  $ axis.minor.ticks.length.theta   : NULL
##  $ axis.minor.ticks.length.r       : NULL
##  $ axis.line                       : list()
##   ..- attr(*, "class")= chr [1:2] "element_blank" "element"
##  $ axis.line.x                     : NULL
##  $ axis.line.x.top                 : NULL
##  $ axis.line.x.bottom              : NULL
##  $ axis.line.y                     : NULL
##  $ axis.line.y.left                : NULL
##  $ axis.line.y.right               : NULL
##  $ axis.line.theta                 : NULL
##  $ axis.line.r                     : NULL
##  $ legend.background               :List of 5
##   ..$ fill         : NULL
##   ..$ colour       : logi NA
##   ..$ linewidth    : NULL
##   ..$ linetype     : NULL
##   ..$ inherit.blank: logi TRUE
##   ..- attr(*, "class")= chr [1:2] "element_rect" "element"
##  $ legend.margin                   : 'margin' num [1:4] 5.5points 5.5points 5.5points 5.5points
##   ..- attr(*, "unit")= int 8
##  $ legend.spacing                  : 'simpleUnit' num 11points
##   ..- attr(*, "unit")= int 8
##  $ legend.spacing.x                : NULL
##  $ legend.spacing.y                : NULL
##  $ legend.key                      : NULL
##  $ legend.key.size                 : 'simpleUnit' num 1.2lines
##   ..- attr(*, "unit")= int 3
##  $ legend.key.height               : NULL
##  $ legend.key.width                : NULL
##  $ legend.key.spacing              : 'simpleUnit' num 5.5points
##   ..- attr(*, "unit")= int 8
##  $ legend.key.spacing.x            : NULL
##  $ legend.key.spacing.y            : NULL
##  $ legend.frame                    : NULL
##  $ legend.ticks                    : NULL
##  $ legend.ticks.length             : 'rel' num 0.2
##  $ legend.axis.line                : NULL
##  $ legend.text                     :List of 11
##   ..$ family       : NULL
##   ..$ face         : NULL
##   ..$ colour       : NULL
##   ..$ size         : 'rel' num 0.8
##   ..$ hjust        : NULL
##   ..$ vjust        : NULL
##   ..$ angle        : NULL
##   ..$ lineheight   : NULL
##   ..$ margin       : NULL
##   ..$ debug        : NULL
##   ..$ inherit.blank: logi TRUE
##   ..- attr(*, "class")= chr [1:2] "element_text" "element"
##  $ legend.text.position            : NULL
##  $ legend.title                    :List of 11
##   ..$ family       : NULL
##   ..$ face         : NULL
##   ..$ colour       : NULL
##   ..$ size         : NULL
##   ..$ hjust        : num 0
##   ..$ vjust        : NULL
##   ..$ angle        : NULL
##   ..$ lineheight   : NULL
##   ..$ margin       : NULL
##   ..$ debug        : NULL
##   ..$ inherit.blank: logi TRUE
##   ..- attr(*, "class")= chr [1:2] "element_text" "element"
##  $ legend.title.position           : NULL
##  $ legend.position                 : chr "right"
##  $ legend.position.inside          : NULL
##  $ legend.direction                : NULL
##  $ legend.byrow                    : NULL
##  $ legend.justification            : chr "center"
##  $ legend.justification.top        : NULL
##  $ legend.justification.bottom     : NULL
##  $ legend.justification.left       : NULL
##  $ legend.justification.right      : NULL
##  $ legend.justification.inside     : NULL
##  $ legend.location                 : NULL
##  $ legend.box                      : NULL
##  $ legend.box.just                 : NULL
##  $ legend.box.margin               : 'margin' num [1:4] 0cm 0cm 0cm 0cm
##   ..- attr(*, "unit")= int 1
##  $ legend.box.background           : list()
##   ..- attr(*, "class")= chr [1:2] "element_blank" "element"
##  $ legend.box.spacing              : 'simpleUnit' num 11points
##   ..- attr(*, "unit")= int 8
##   [list output truncated]
##  - attr(*, "class")= chr [1:2] "theme" "gg"
##  - attr(*, "complete")= logi TRUE
##  - attr(*, "validate")= logi TRUE
#plot titik dengan jitter
library(ggplot2)
ggplot(lizard, aes (x= total_length, y= weight)) +
  geom_jitter()

  labs(title ="plot titik - titik lizard", x = "total_length", y = "common_name")
## $x
## [1] "total_length"
## 
## $y
## [1] "common_name"
## 
## $title
## [1] "plot titik - titik lizard"
## 
## attr(,"class")
## [1] "labels"
#histogram untuk total length
library (ggplot2)
ggplot(lizard, aes (x= total_length)) +
  geom_histogram() +
  labs(title ="plot titik - titik lizard", x = "total_length", y = "common_name")
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.

#bar plot untuk common name
library (ggplot2)
ggplot(lizard, aes (y = common_name)) +
  geom_bar() +
  labs(title ="plot titik - titik lizard", x = "total_length", y = "common_name")

#Histogram untuk Weight dengan Kustomisasi
library (ggplot2)
ggplot(lizard, aes (x=weight)) +
  geom_histogram(color= "orange",fill="magenta",size = 2, shape=16,linetype="dotted") +
labs(title ="dinding lizard", x = "weight", y = "count")
## Warning: Using `size` aesthetic for lines was deprecated in ggplot2 3.4.0.
## ℹ Please use `linewidth` instead.
## This warning is displayed once every 8 hours.
## Call `lifecycle::last_lifecycle_warnings()` to see where this warning was
## generated.
## Warning in geom_histogram(color = "orange", fill = "magenta", size = 2, :
## Ignoring unknown parameters: `shape`
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.

#plot titik dasar
ggplot(lizard, aes (x= total_length, y= weight)) +
  geom_point(color= "blue", size = 2,shape= 16) +
  labs(x = "total_length", y = "weight")

#Plot Titik dengan Warna Berdasarkan Common Name
ggplot(lizard, aes (x= total_length, y= weight,color=common_name)) +
  geom_point(size = 2,shape= 16) +
  labs(x = "total_length", y = "weight", color="common name")

#Load packages
library(gapminder)
library(ggplot2)
library(gganimate)
#import data
library(gapminder)
data<-gapminder
data
## # A tibble: 1,704 × 6
##    country     continent  year lifeExp      pop gdpPercap
##    <fct>       <fct>     <int>   <dbl>    <int>     <dbl>
##  1 Afghanistan Asia       1952    28.8  8425333      779.
##  2 Afghanistan Asia       1957    30.3  9240934      821.
##  3 Afghanistan Asia       1962    32.0 10267083      853.
##  4 Afghanistan Asia       1967    34.0 11537966      836.
##  5 Afghanistan Asia       1972    36.1 13079460      740.
##  6 Afghanistan Asia       1977    38.4 14880372      786.
##  7 Afghanistan Asia       1982    39.9 12881816      978.
##  8 Afghanistan Asia       1987    40.8 13867957      852.
##  9 Afghanistan Asia       1992    41.7 16317921      649.
## 10 Afghanistan Asia       1997    41.8 22227415      635.
## # ℹ 1,694 more rows
#membuat plot dasar statis
library(gapminder)
library(ggplot2)
gapminder_plot <- ggplot(
  gapminder, 
  aes(x = gdpPercap, y=lifeExp)
  ) +
  geom_point(alpha = 0.6) +
  scale_x_log10() +
  labs(x = "GDP per capita", y = "Life expectancy")
gapminder_plot    

#menambahkan elemen ('aes')
gapminder_plot <- ggplot(
  gapminder, 
  aes(x = gdpPercap, y=lifeExp, size = pop, colour = continent)
  ) +
  geom_point(alpha = 0.6) +
  scale_x_log10() +
  scale_color_viridis_d(option = "viridis") +
  labs(x = "GDP per capita", y = "Life expectancy")
gapminder_plot

##menambahkan efek transisi menggunakan gganimate

library(ggplot2)
library(gganimate)
library(gapminder)
gapminder_plot <- ggplot(gapminder, aes(x = gdpPercap, y = lifeExp, size = pop, color = continent)) +
  geom_point(alpha = 0.7, show.legend = TRUE) +
  scale_x_log10() +
  labs(
    x = "GDP per Capita (log scale)",
    y = "Life Expectancy",
    title = "Year: {frame_time}",
    subtitle = "Bubble size represents population",
    color = "Continent",
    size = "Population"
  ) +
  theme_minimal()
# 1. Transisi waktu dengan animasi sederhana
animated_plot1 <- gapminder_plot + 
  transition_time(year) +
  labs(title = "Year: {frame_time}")
animate(animated_plot1, nframes = 200, fps = 20)

# 2. Animasi dengan facet_wrap berdasarkan kontinen
animated_plot2 <- gapminder_plot + 
  facet_wrap(~continent) +
  transition_time(year) +
  labs(title = "Year: {frame_time}")
animate(animated_plot2, nframes = 200, fps = 20)

# 3. Animasi dengan view_follow untuk fokus pada sumbu tetap
animated_plot3 <- gapminder_plot + 
  transition_time(year) +
  labs(title = "Year: {frame_time}") +
  view_follow(fixed_y = TRUE)
animate(animated_plot3, nframes = 200, fps = 20)

# 4. Animasi dengan efek shadow_wake
animated_plot4 <- gapminder_plot + 
  transition_time(year) +
  labs(title = "Year: {frame_time}") +
  shadow_wake(wake_length = 0.1, alpha = FALSE)
animate(animated_plot4, nframes = 200, fps = 20)

# 5. Animasi dengan efek shadow_mark
animated_plot5 <- gapminder_plot + 
  transition_time(year) +
  labs(title = "Year: {frame_time}") +
  shadow_mark(alpha = 0.3, size = 0.5)
animate(animated_plot5, nframes = 200, fps = 20)

Referensi

Jika ada bagian yang kurang jelas atau memerlukan penyesuaian, silakan tambahkan komentar atau revisi lebih lanjut untuk penyempurnaan dokumen ini.